--- layout: jupyter title: "Jekyll, Say Hi to Jupyter Notebook Again!" date: 2022-08-07 09:08:25 +0000 background: '/img/posts/bgp2.jpg' categories: - jekyll --- HelloJekyll

So I've spent the weekend figuring out how to properly embed Jupyter notebooks into my Jekyll site. Overall, I'm happy with my results. I managed to adjust the font-colors of the various CSS classess and embed my plots nicely in here. I also learned how to include my own images and embed audio into my Jupyter notebooks and have them play after the conversion to html.


My current procedure for doing this is as follows:

  1. Download Jupyter Notebook (.ipynb) as a .html
  2. Copy the contents of the resulting html file into a Jekyll post with the appropriate header
  3. Remove the DOCTYPE and html lines contained within the html file made from the Jupyter notebook

In addition to those steps, I also slightly modified the 'default.html' file and made a 'jupyter.html' file based on the files that came from the Jekyll website template I'm using. This allowed me to preserve the post headers and control the footers of my site since they were behaving kinda wonky (i.e., the image associated with the post was not showing up, the jupyter notebook was off-center, and the footer links were messed up). That being said, if you follow the above three steps, you'll be able to see your Jupyter notebook in your Jekyll site.


I also tried (perhaps an instance of me trying to get too fancy too soon) to embed interactive plots using plotly in my jekyll site. Unfortunately, that has proven to be quite challenging so far since the conversion from the .ipynb to html using nbconv seems to have an issue with the javascript associated with plotly. I've tried modifying the javascript but haven't been successful yet in rendering my interactive visualizations.

If you are trying to use plotly in your Jupyter Notebooks and have them displayed in your Jekyll site, here are a few links that may be useful to you:

  1. https://davistownsend.github.io/blog/PlotlyBloggingTutorial/
  2. https://stackoverflow.com/questions/50546971/embedding-plotly-interactive-graphs-into-blog-without-losing-animation
  3. https://stackoverflow.com/questions/72378397/about-plotly-how-can-i-post-it-for-my-github-pages
In [76]:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D 
import seaborn as sns
import numpy as np
import pandas as pd
import random
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
from plotly.graph_objs import Scatter, Figure, Layout
import plotly
import plotly.graph_objs as go
config={'showLink': False, 'displayModeBar': False}
init_notebook_mode(connected=False)
import json
from IPython.core.display import display, HTML
config={'showLink': False, 'displayModeBar': False}
import IPython
from IPython.display import display, HTML
In [53]:
#Hi!
print("Hello Jekyll from the Jupyter Notebook!! :]")
Hello Jekyll from the Jupyter Notebook!! :]
In [54]:
#Make random data to plat
xs = [random.gauss(0, 10) for _ in range(100)]
ys = [random.gauss(0, 10)for _ in range(100)]
zs = [random.gauss(0, 10) for _ in range(100)]
In [55]:
#Make a scatter plot from random data
sns.set(rc={'figure.figsize':(16.7,8.27)})
sns.set(font_scale = 2)
plt.scatter(xs, ys)
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Random plot")
plt.show()
In [56]:
#Make histogram of generated data
sns.color_palette("mako", as_cmap=True)
sns.histplot(ys, bins = 20, discrete = True, kde = True, color = 'red',  alpha=0.5)
sns.histplot(xs, bins = 20, discrete = True, kde = True, color = 'blue', alpha=0.5)
sns.set(rc={'figure.figsize':(16.7,8.27)})
sns.set(font_scale = 2)
plt.legend(labels=["Rand y","Rand x"])
Out[56]:
<matplotlib.legend.Legend at 0x1ecbf0d57c8>
In [57]:
#Make a 3D parametric curve
ax = plt.figure().add_subplot(projection='3d')
sns.set(rc={'figure.figsize':(8.7,8.27)})

# Prepare arrays x, y, z
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)

ax.plot(x, y, z, label='parametric curve')
ax.legend()

plt.show()
In [75]:
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/volcano.csv')

data = [go.Surface(z=df.values.tolist(), colorscale='Viridis')]

layout = go.Layout(
    width=600,
    height=500,
    autosize=False,
    scene=dict(
        xaxis=dict(
            gridcolor='rgb(255, 255, 255)',
            zerolinecolor='rgb(255, 255, 255)',
            showbackground=True,
            backgroundcolor='rgb(230, 230,230)'
        ),
        yaxis=dict(
            gridcolor='rgb(255, 255, 255)',
            zerolinecolor='rgb(255, 255, 255)',
            showbackground=True,
            backgroundcolor='rgb(230, 230, 230)'
        ),
        zaxis=dict(
            gridcolor='rgb(255, 255, 255)',
            zerolinecolor='rgb(255, 255, 255)',
            showbackground=True,
            backgroundcolor='rgb(230, 230,230)'
        ),
        aspectratio = dict(x=1, y=1, z=0.7),
        aspectmode = 'manual'
    )
)

updatemenus=list([
    dict(
        buttons=list([   
            dict(
                args=['type', 'surface'],
                label='3D Surface',
                method='restyle'
            ),
            dict(
                args=['type', 'heatmap'],
                label='Heatmap',
                method='restyle'
            )             
        ]),
        direction = 'down',
        pad = {'r': 0, 't': 0},
        showactive = True,
        x = 1.25,
        xanchor = 'left',
        y = 1.1,
        yanchor = 'top' 
    ),
])

annotations = list([
    dict(text='', x=0, y=1.085, yref='paper', align='left', showarrow=False)
])
layout['updatemenus'] = updatemenus
layout['annotations'] = annotations

fig = dict(data=data, layout=layout)
iplot(fig,show_link=False , config = config)

import plotly.io as pio

pio.write_html(fig, file='figure.html', auto_open=True)
{% include figure_3.html %}

Embedding an image via html into Jupyter Notebook in Jekyll

Here's a picture of my cat for you :]

Embedding an audio file into Jupyter Notebook in Jekyll

Below is a sample of my guitar playing :]

In [39]:
#Loading an audio file into notebook
IPython.display.Audio("CrimsonCloverCover.mp3")
Out[39]:
In [ ]: